package com.fangque.kepp.framework.user.controller;

import com.fangque.kepp.framework.result.ResultBean;
import com.fangque.kepp.framework.user.entity.User;
import com.fangque.kepp.framework.user.service.UserServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登录部分处理由 JwtLoginFilter.attemptAuthentication 中的 authenticationManager.authenticate(..)处理
 * @author : liyk
 * @date : 2019/11/1 10:54
 * @version 1.0
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserServiceImpl userService;

    @RequestMapping(value = "/hello")
    public ResultBean hello(HttpServletRequest request, HttpServletResponse response) {
        return ResultBean.ok("Hello World!");
    }

    @RequestMapping(value = "register", method = RequestMethod.POST)
    public ResultBean userRegister(String username, String password) {
        User user = userService.userRegister(username, password);
        if (user != null) {
            return ResultBean.ok("注册成功!");
        } else {
            return ResultBean.error("用户名已存在，注册失败!");
        }
    }

    @RequestMapping(value = "logout", method = RequestMethod.POST)
    public ResultBean userLogout(HttpServletRequest request, HttpServletResponse response) {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null) {
            new SecurityContextLogoutHandler().logout(request, response, auth);
        }
        return ResultBean.ok("成功登出!");
    }

}
